<?php





namespace app\admin\model;



use app\admin\model\Common;

use think\Exception;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\common\traits\UserInfoTrait;

use app\crm\model\ReserveandLost;



/**

 * 优惠券model

 * Class Goods

 * @package app\shop\model

 * @author Mr.Liu

 * @create 2021-09-15 15:01

 */

class Coupon extends Common

{

    use SoftDelete;

    use ActionRecordTrait,UserInfoTrait;



    /**

     * 表名

     * @var string

     */

    //protected $pk = 'id';

    protected $name = 'coupon';

    protected $deleteTime = 'delete_time';

    protected $defaultSoftDelete = 0;

    protected $autoWriteTimestamp = true;



    // 定义时间戳字段名

    /**

     * 获取优惠券列表

     * 是否不分页  no_page  0/null 分页 1不分页

     * @param  array $request 请求参数

     * @return array

     * @author Mr.Liu

     * @create 2021-09-25 17:51

     */

    public function getDataList(array $request): array

    {

        try {

            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            $where =  $map['where'] ?? [];

            if(!$where){

                $id = isset($map['id']) && $map['id'] ? $map['id'] : [];

                if ($id) {

                    if (!is_array($id)) {

                        $id = [$id];

                    }

                    array_push($where, ['id', 'in', $id]);

                }

                $type =isset($map['type']) && $map['type'] ? trim($map['type']) : '';

                $type && array_push($where, ['type', '=', $type]);

                $search    = isset($map['name']) && $map['name'] ? trim($map['name']) : '';

                $search && array_push($where, ['name', 'like', '%'.$search.'%']);

            }

            $dataCount  = $this->where($where)->count();

            if ($dataCount) {

                $field = $request['map']['field'] ?? '';

                if(!$field){

                    $field = ['id', 'name','type', 'use_type', 'denomination','use_threshold', 'start_time','end_time','goods_id','provide_type','provide_time','provide_status'];

                }

                $list = $this->when(!(isset($map['no_page']) && $map['no_page']) ,function($query) use ($request){

                        $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);

                    })

                    ->where($where)

                    ->order('id DESC')

                    ->field($field)->select()->toArray();

                $time=time();

                if ($list) {

                    foreach($list as &$v){

                        if ($time<$v['start_time'])

                        {

                            $v['status_desc']='未启用';

                        }elseif ($time>$v['end_time'])

                        {

                            $v['status_desc']='已过期';

                        }else{

                            $v['status_desc']='已启用';

                        }

                        $v['provide_status_desc']=$v['provide_status'] == 1?'已发放':'未发放';

                        if(isset($v['create_user_id'])){

                            $v['create_user_name'] = $v['create_user_id'] ? $this->getUserValue($v['   '],'realname') : '';

                        }

                        if ($v['goods_id'])

                        {

                            $goods_list=Db::name('shop_goods')->where('id','in',$v['goods_id'])->field('name')->select();

                            $goods_list =  json_decode( json_encode( $goods_list),true);

                            $goods_name=array_column($goods_list,'name');

                            $names=implode(",",$goods_name);

                        }

                       switch ($v['type'])

                        {

                            case 1:

                                $v['type']="满减券";

                                $v['rule']="满".$v['use_threshold'].'减'.$v['denomination'];

                                break;

                            case 3:

                                $v['type']="满赠券";

                                $v['rule']="满".$v['use_threshold'].'赠'.$names;

                                break;

                             case 4:

                                 $v['type']="兑换券";

                                 $v['rule']="可兑换".$names;

                                 break;

                                 default;

                        }

                        $v['provide_time']=date("Y-m-d",$v['provide_time']);

                        $v['start_time']=date("Y-m-d",$v['start_time']);

                        $v['end_time']=date("Y-m-d",$v['end_time']);

                        unset($v['create_user_id']);

                    }

                }

            }

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }





    /**

     * 优惠券详情

     * @param array $request

     * @return array

     * @author Mr.Li

     * @create 2021-09-20 16:25

     */

    public function getDataDetail(array $request): array

    {

        $goodsDetail = [];

        try {

            $id = $request['id'] ?? 0;

            if(!$id){

                $this->error = '请输入优惠券id';

                return [];

            }

            $goodsField = $request['goods_field'] ?? '';

            if(!$goodsField){

                $goodsField = ['*'];

            }

            $detail = self::field($goodsField)->find($id);



            if(!empty($detail)){

                $goodsDetail = $detail->toArray();

                if(isset($goodsDetail['create_user_id'])){

                    $goodsDetail['create_user_name'] = $this->getUserValue($goodsDetail['create_user_id'],'realname');

                }

            }else

            {

                $this->error = '优惠券不存在';

                return [];

            }

            $goodsDetail['start_time']=date("Y-m-d",$goodsDetail['start_time']);

            $goodsDetail['end_time']=date("Y-m-d",$goodsDetail['end_time']);

            $goodsDetail['provide_time']=date("Y-m-d",$goodsDetail['provide_time']);

            $goodsDetail['provide_status_desc']=$goodsDetail['provide_status']==1?'已发放':'未发放';

            $time=time();

            if ($time<$goodsDetail['start_time'])

            {

                $goodsDetail['status_desc']='未启用';

            }elseif ($time>$goodsDetail['end_time'])

            {

                $goodsDetail['status_desc']='已过期';

            }else{

                $goodsDetail['status_desc']='已启用';

            }

            $type= $request['type'] ?? 0;

            $field='id,name,category_id,goods_sn,kingdee_code,goods_price,spec_name,unit_code,unit_name,is_project';

                if ($type)

                {

                    if ($detail['type']==1)

                    {

                        //满减，需要修改代码固定满减商品

                        $goods= Db::name('shop_goods')->where('kingdee_code','101.12.098')->field($field)->select();

                        $goods=$goods->toArray();

                        $goods[0]['goods_price']=$goodsDetail['denomination'];

                        $goodsDetail['goodsList']=$goods;

                    }else

                    {

                        $goodsDetail['goodsList']= Db::name('shop_goods')->where('id','in',$goodsDetail['goods_id'])->field($field)->select();

                    }

                }else

                {

                    $goodsDetail['goodsList']= Db::name('shop_goods')->where('id','in',$goodsDetail['goods_id'])->field($field)->select();

                }



            return $goodsDetail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }





    /**

     * 优惠券公共判断

     * @param  array $request 请求参数

     * @return bool

     * @author Mr.Liu

     * @create 2021-09-25 11:25

     */



    function validates($data)

    {

        $result=['status'=>1,'error'=>''];



        if ($data['type'] == 1)

        {

            if (!isset($data['denomination'])||empty($data['denomination']))

            {

                $result['error']='满减券面额必须填写';

                $result['status']=0;

                return $result;

            }elseif ($data['denomination'] <0.01)

            {

                $result['error']='满减券面额金额填写不正确';

                $result['status']=0;

                return $result;

            }

        }





        if ($data['type'] > 1 && $data['goods_type'] == 1)

        {

            if (!isset($data['goodsList']))

            {

                $result['error']='商品必须选择';

                $result['status']=0;

                return $result;

            }

            $ids=array_column($data['goodsList'],'id');

            if (empty($ids))

            {

                $result['error']='商品必须选择';

                $result['status']=0;

                return $result;

            }

            $goods_id=implode(',',$ids);

            $result['error']='数据成功';

            $result['status']=2;

            $result['data']=$goods_id;

            return $result;

        }



        if (strtotime($data['end_time'])<time())

        {

            $result['error']='结束日期不能早于当前时间';

            $result['status']=0;

            return $result;

        }





        return  $result;

    }



    /**

     * 新增优惠券

     * @param  array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-09-23 11:25

     */

    public function addData(array $request): bool

    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $is_vip = $request['is_vip'] ?? '0';

        if($is_vip == '0'){

            try {

                $validate = new \app\admin\validate\Coupon();

                if (!$validate->scene('create')->check($request)) {

                    $this->error = $validate->getError();

                    return false;

                }

            }catch (\Exception $e) {

                $this->error = $e->getMessage();

                return false;

            }

        }


        $result=$this->validates($request);

        $goods_id=0;

        if (!$result['status'])

        {

            $this->error = $result['error'];

            return false;

        }elseif($result['status']>1){

            $goods_id=$result['data'];

        }

        Db::startTrans();

        try {

            $time = time();

            // 验证

            $data = [

                'type'                  => $request['type'],

                'use_type'              => $request['use_type'],

                'name'                  => trim($request['name']),

                'denomination'          => isset($request['denomination']) ? $request['denomination'] : 0,

                'goods_id'              => $goods_id,

                'limit_number'          => isset($request['limit_number']) ? $request['limit_number'] : 1,

                'use_threshold'         => isset($request['use_threshold']) ? $request['use_threshold'] : 0,

                'start_time'            => strtotime($request['start_time']),

                'end_time'              => strtotime($request['end_time']),

                'desc'                  => isset($request['desc']) ? trim($request['desc']) : '',

                'create_user_id'        => $request['user']['id'],

                'update_time'           => $time,

                'create_time'           => $time,

                'is_vip'                => $is_vip,

            ];

            $this->create($data);

            Db::commit();

            $this->error = '添加成功';

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '添加失败';

        return false;



    }



    /**

     * 更新优惠券

     * @param array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-05-26 11:33

     */

    public function saveData(array $request): bool

    {

        // 验证

        try{

            $validate = new \app\admin\validate\Coupon();

            if (!$validate->scene('update')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch(\Exception $e){

            $this->error =$e->getMessage();

            return false;

        }



        $result=$this->validates($request);

        $goods_id=0;

        if (!$result['status'])

        {

            $this->error = $result['error'];

            return false;

        }elseif($result['status']>1){

            $goods_id=$result['data'];

        }

        $id = $request['id'] ?? 0;

        Db::startTrans();

        try {

            $coupon = $this->field('id,type,provide_status,status')->find($id);

            if($coupon){

                $coupon = $coupon->toArray();

            }else{

                $this->error = '优惠券不存在';

                return false;

            }

            if ($coupon['provide_status'] == 1)

            {

                $this->error = '已发放优惠券不可编辑';

                return false;

            }

            if ($request['type'] !== $coupon['type'] )

            {

                $this->error = '优惠券类型不可以更改';

                return false;

            }

            if ($coupon['status'] == 2)

            {

                $this->error = '已过期优惠券不可编辑';

                return false;

            }



            $time=time();

            $data = [

                'type'                  => $request['type'],

                'use_type'              => $request['use_type'],

                'name'                  => trim($request['name']),

                'denomination'          => isset($request['denomination']) ? $request['denomination'] : 0,

                'goods_id'              => $goods_id,

                'limit_number'          => isset($request['limit_number']) ? $request['limit_number'] : 1,

                'use_threshold'         => isset($request['use_threshold']) ? $request['use_threshold'] : 0,

                'start_time'            => strtotime($request['start_time']),

                'end_time'              => strtotime($request['end_time']),

                'desc'                  => isset($request['desc']) ? trim($request['desc']) : '',

                'create_user_id'        => $request['user']['id'],

                'update_time'           => $time

            ];



            $this->where(['id'=>$id])->update($data);

            Db::commit();

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '更新失败';

        return false;

    }



    /**

     * 删除优惠券

     * @param  array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-05-26 15:09

     */

    public function deleteData(array $request): bool

    {

        try {



            $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];

            if (!$requestId) {

                $this->error = '参数错误';

                return false;

            }

            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);

            $where = [

                ['id', 'in', $idArr]

            ];

            Db::startTrans();

            $bool = self::destroy(function($query) use ($where){

                $query->where($where);

            });

            if ($bool) {

                Db::commit();

            }else{

                Db::rollback();

                $this->error = '删除失败';

                return false;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '删除成功';

        return true;

    }



    /**

     * 发放优惠券

     * @param array $request

     * @return bool

     * @author Mr.LiU

     * @create 2021-11-04 11:12

     */

    public function couponProvide(array $request): bool

    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;
        // 验证

        try{

            $validate = new \app\admin\validate\Coupon();

            if (!$validate->scene('provide')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch(\Exception $e){

            $this->error =$e->getMessage();

            return false;

        }

        $id = $request['id'] ?? 0;

        $provide_type=$request['provide_type'];

        $operator_id=$request['user']['id'];

        Db::startTrans();

        try {

        $coupon = $this->field('id,type,provide_status,status,name')->find($id);

        if($coupon){

            $coupon = $coupon->toArray();

        }else{

            $this->error = '优惠券不存在';

            return false;

        }

        if ($coupon['provide_status'] == 1)

        {

            $this->error = '已发放优惠券不可再次发放';

            return false;

        }

        if ($coupon['status'] == 2)

        {

            $this->error = '已过期优惠券不可发放';

            return false;

        }

            $time = time();

            $dataListArr = $request['dataList'];



            if($provide_type == 5){

                $provideDataList['coupon_id'] = $id;

                $provideDataList['create_time'] = $time;

                $provideDataList['data_id'] = '5';

                $provideDataList['data_name'] = '条件筛选';

                $provideDataList['provide_create_user_id'] = $operator_id;//发放人




                $shop_list = $dataListArr['shop_list'] ?? [];

                $memberRank = $dataListArr['memberRank'] ?? [];

                $create_time = $dataListArr['create_time'] ?? [];

                $come_time = $dataListArr['come_time'] ?? [];

                $cj_time = $dataListArr['cj_time'] ?? [];

                $scar_id = $dataListArr['scar_id'] ?? [];

                $source_id = $dataListArr['source_id'] ?? [];

                $member_classification = $dataListArr['member_classification'] ?? [];

                $member_label = $dataListArr['member_label'] ?? "";

                $baoyou = $dataListArr['baoyou'] ?? "";



                $searchWhere = []; // 筛选条件

                $searchData = [];

                if($shop_list){
                    // echo '门店';
                    array_push($searchWhere,['c.shop_id','in',$shop_list]);

                    $shop_name = Db::name('shop')->where('shop_id','in',$shop_list)->column('shop_name');

                    $provideDataList['shop_names'] = implode(',',$shop_name);

                }

                if($memberRank){
                    // echo '会员等级';
                    array_push($searchWhere,['c.membership_leve','in',$memberRank]);

                    array_push($searchWhere,['c.join_time','<',$time]);

                    array_push($searchWhere,['c.be_overdue_time','>',$time]);

                    $grade_name = Db::name('customer_grade')->where('id','in',$memberRank)->column('name');

                    $provideDataList['member_names'] = implode(',',$grade_name);

                }

                if($create_time){
                    // echo '创建信息时间';
                    $stime = strtotime($create_time[0]);

                    $etime = strtotime($create_time[1])+86399;

                    array_push($searchWhere,['c.create_time','between',"$stime,$etime"]);

                    $provideDataList['create_times'] = implode('至',$create_time);

                }

                if($come_time){
                    // echo '顾客进店时间';
                    $stime = strtotime($come_time[0]);

                    $etime = strtotime($come_time[1])+86399;

                    array_push($searchWhere,['c.first_time|c.second_time','between',"$stime,$etime"]);

                    $provideDataList['come_time'] = implode('至',$come_time);

                }

                if($cj_time){
                    // echo '顾客成交时间';
                    $stime = strtotime($cj_time[0]);

                    $etime = strtotime($cj_time[1])+86399;

                    array_push($searchWhere,['c.cj_time','between',"$stime,$etime"]);

                    $provideDataList['cj_time'] = implode('至',$cj_time);

                }

                if($scar_id){
                    // echo '疤痕类型';

                    array_push($searchWhere,['cs.customer_setting_id_type','in',$scar_id]);

                    $scar_name = Db::name('setting')->where('id','in',$scar_id)->column('name');

                    $provideDataList['scar_nams'] = implode(',',$scar_name);

                }

                if($source_id){
                    // echo '顾客进店时间';

                    array_push($searchWhere,['c.source_id','in',$source_id]);

                    $source_name = Db::name('setting')->where('id','in',$source_id)->column('name');

                    $provideDataList['source_names'] = implode(',',$source_name);

                }

                if($member_classification){
                    // echo '顾客进店时间';

                    array_push($searchWhere,['c.member_classification','in',$member_classification]);

                    $member_arr = [
                        '70' => 'D类顾客',
                        '71' => 'C类顾客',
                        '72' => 'B类顾客',
                        '73' => 'A类顾客',
                    ];

                    $member_name = [];

                    foreach ($member_classification as $key => $value) {

                        array_push($member_name,$member_arr[$value]);

                    }

                    $provideDataList['member_types'] = implode(',',$member_name);

                }

                if($member_label){
                    // echo '顾客进店时间';

                    array_push($searchWhere,['c.member_label','=',$member_label]);

                    $member_label_name = Db::name('setting')->where('id','=',$member_label)->column('name');

                    $provideDataList['member_label_name'] = implode(',',$member_label_name);

                }

                if($baoyou){
                    // echo '保有顾客，流失预警，流失顾客';

                    $date = date("Y-m-d");

                    $shop_where = [];

                    array_push($shop_where,['shop_type','=','2']);

                    array_push($shop_where,['type','=','1']);

                    array_push($shop_where,['status','=','1']);

                    $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

                    $model = new ReserveandLost();

                    $cj_customer = $model->cj_customer($shopIds,[]);



                    switch ($baoyou) {

                        case '1': // 保有顾客

                            $baoyou_name = '保有顾客';

                            $res_customer = $model->baoyou_customer($cj_customer,$date);

                            break;

                        case '2': // 流失预警

                            $baoyou_name = '流失预警';

                            $res_customer = $model->warning_customer($cj_customer,$date,'','','');

                            break;

                        case '3': // 流失顾客

                            $baoyou_name = '流失顾客';

                            $res_customer = $model->lost_customer($cj_customer,$date);

                            break;

                    }

                    // echo $baoyou_name.':'.count($res_customer);
                    // echo '<br/>';

                    array_push($searchWhere,['c.id','in',$res_customer]);

                    $provideDataList['baoyou_name'] = $baoyou_name;

                }


                $customer_ids = Db::name('customer')->alias('c')
                                ->join('customer_scar cs', 'cs.customer_id=c.id', 'LEFT')
                                ->where($searchWhere)->column('c.id');

                // echo '预计发放顾客数:'.count($customer_ids);
                // echo '<br/>';

                $customer_ids = array_unique($customer_ids);

                // echo '去重后预计发放顾客数:'.count($customer_ids);
                // echo '<br/>';exit;

                if(count($customer_ids)<='1'){

                    $this->error = '所选条件包含0个客户';

                    return false;

                }

                $provideDataList['should_send'] = count($customer_ids);

                $provide=Db::name('coupon_provide')->insertGetId($provideDataList);

                // exit;

            }else{

                $data_ids = array_column($dataListArr, 'data_id');

                foreach ($dataListArr as $k => $v) {

                    $provideDataList[$k]['coupon_id'] = $id;

                    $provideDataList[$k]['create_time'] = $time;

                    $provideDataList[$k]['data_id'] = $v['data_id'];

                    $provideDataList[$k]['data_name'] = $v['data_name'];

                    $provideDataList[$k]['provide_create_user_id'] = $operator_id;//发放人

                }

                $provide=Db::name('coupon_provide')->insertAll($provideDataList);

            }




            //发放创建成功，处理会员发券

            if ($provide)

            {

                //指定会员

                if ($provide_type == 4 )

                {

                    $customers=$data_ids;

                }else if($provide_type == 5){

                    $customers = $customer_ids;

                }else

                {

                    $customers=$this->provide($data_ids,$provide_type);//获取会员id合集 黄璋接口补充

                }

                $had_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','=',$id],['customer_id','in',$customers]])->column('customer_id');

                $customers = array_diff($customers,$had_cardIds);

                if(count($customers)<='1'){

                    $this->error = '所选客户已经发放该优惠券了，请勿重复发放！';

                    return false;

                }

                foreach ($customers as $k => $v) {

                    $provideCustomerList[$k]['coupon_id'] = $id;

                    $provideCustomerList[$k]['create_time'] = $time;

                    $provideCustomerList[$k]['customer_id'] = $v;

                }

                $res = Db::name('coupon_provide_customer')->insertAll($provideCustomerList);

                $save = [

                    'actual_send' => $res,

                ];

                $provide_bool = Db::name('coupon_provide')->where(['id'=>$provide])->update($save);

                $data = [

                    'provide_create_user_id'     => $operator_id,//发放人

                    'provide_status'    => 1, // 发放状态

                    'provide_type'       => $provide_type,//发放类型

                    'provide_time'  => $time, // 发放时间

                ];

                $bool = $this->where(['id'=>$id])->update($data);

                // 添加操作记录

                $operator_name= Db::name('admin_user')->where(['id' => $operator_id])->value('realname');

                $data_name = array_column($dataListArr, 'data_name');

                $data_name_str = implode('|', $data_name);

                $content = '发放优惠券：【'. $operator_name . '】发放了【' . $coupon['name'] . '】' . '的优惠券，发送给了：' . $data_name_str . '】';

                $code = [];

                $code = $data;

                $code['provideCustomerList']  = $provideCustomerList;

                $this->addActionRecord($operator_id,'admin_provide_create',$id,$content,'admin','coupon',json_encode($code));



                Db::commit();

                $this->error = '发放成功';

                return true;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

    }



    /**

     * $provide_type 1标签选择 2门店选择 3 会员等级 4 指定会员

     * 数据id 数据集

     */

    public function provide($data_ids,$provide_type): array

    {

        $userIds = array();

        if (!is_array($data_ids) || empty($data_ids) || !in_array($provide_type,array(1,2,3))){

            return $userIds;

        }

        //设置搜索条件

        $where = array();

        array_push($where,['status','=',1]);

        if ($provide_type == 1) {        // 标签选择

            // code...

            foreach ($data_ids as $key => $val){

                $thisUserIds = db::name('customer')->where($where)->whereFindInSet('member_label',$val)->column('id');

                $userIds = array_merge($userIds,$thisUserIds);

            }

        }else {

            if ($provide_type == 2) {  // 门店选择

                // code...

                array_push($where,['shop_id','in',$data_ids]);

            }else if ($provide_type == 3) {  // 会员等级

                // code...

                array_push($where,['membership_leve','in',$data_ids]);

                array_push($where,['be_overdue_time','>',time()]); // 未过期会员

            }

        $userIds = db::name('customer')->where($where)->column('id');

        }

        return $userIds;

    }





    /**

     * 优惠券发放详情

     * @param array $request

     * @return array

     * @author Mr.Liu

     * @create 2021-11-5 16:25

     */

    public function getProvideDetail(array $request): array

    {

        $provideDetail = [];



        try {

            $id = $request['id'] ?? 0;

            if(!$id){

                $this->error = '请输入优惠券id';

                return [];

            }

            $coupon = $this->field('id,provide_create_user_id,provide_type,provide_time')->find($id);



            if(empty($coupon)){

                $this->error = '优惠券不存在';

                return false;

            }else{

               $coupon=$coupon->toArray();

            }

            $detail = Db::name('coupon_provide')->where(['coupon_id' => $id])->order('id DESC')->select()->toArray();

            // echo "<pre>";
            // print_r($detail);
            // echo "</pre>";
            // exit;

            if (!empty($detail))

            {

                foreach ($detail as $key => $value) {

                    $one['data_name'] = $value['data_name'] ?? '';

                    $one['create_time'] = $value['create_time'] > 0 ? date('Y-m-d H:i:s',$value['create_time']) : '';

                    $one['provide_create_user_name'] = $this->getUserValue($value['provide_create_user_id'],'realname');

                    $one['shop_names'] = $value['shop_names'] ?? '';

                    $one['member_names'] = $value['member_names'] ?? '';

                    $one['create_times'] = $value['create_times'] ?? '';

                    $one['come_times'] = $value['come_times'] ?? '';

                    $one['cj_times'] = $value['cj_times'] ?? '';

                    $one['scar_nams'] = $value['scar_nams'] ?? '';

                    $one['source_names'] = $value['source_names'] ?? '';

                    $one['member_types'] = $value['member_types'] ?? '';

                    $one['member_label_name'] = $value['member_label_name'] ?? '';

                    $one['should_send'] = $value['should_send'] ?? '';

                    $one['actual_send'] = $value['actual_send'] ?? '';

                    $one['baoyou'] = $value['baoyou_name'] ?? '';

                    array_push($provideDetail,$one);

                }
                // $provideDetail['dataList']=$detail;

                // if(isset($coupon['provide_create_user_id'])) {

                //      $provideDetail['provide_create_user_name'] = $this->getUserValue($coupon['provide_create_user_id'],'realname');

                //  }

                // $provideDetail['provide_time']=date("Y-m-d",$coupon['provide_time']);

                // $provideDetail['provide_type']=$coupon['provide_type'];


            }

            return $provideDetail;



        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }















    /**

     * 根据条件获取信息

     * @param  array $where 查询条件

     * @param  array $field 查询字段

     * @return array

     * @author Mr.Liu

     * @create 2021-09-20 10:51

     */

    public function getGoodsList(array $where = [], array $field = []): array

    {

        try {

            $list = $this->where($where)->field($field)->select()->toArray();

        } catch (\Exception $e) {

        }



        return isset($list) && $list ? $list : [];

    }





    /**

     * 更新同步金蝶优惠券库存

     * @author Mr.Li

     * @create 2021-07-08 16:52

     */

    public function syncKingdeeStock()

    {

        try {



            $sqlserverConn =  \think\facade\Db::connect('sqlsrv');

            $sql = "exec proc_Dxj_kxkc 'kc'";

            //$sql = "exec DXJ_WLDWHS  'wl'";

            $sqlRes = $sqlserverConn->query($sql);

            $sqlRes = $sqlRes[0] ?? [];

            //print_r($sqlRes);

            if($sqlRes){

                foreach($sqlRes as $v){

                    $insertUnitList[$v['ckbm'].'_'.$v['Wlbm']] = [

                        'warehouse_kingdee_code'      => $v['ckbm'],

                        'goods_kingdee_code'          => $v['Wlbm'],

                        'inventory_quantity'          => $v['Dbzkxkc'],

                    ];

                }



                //获取数据库仓库库存信息

                $goodsStockData = [];

                $stockData = Db::name('shop_goods_stock')->where('id','>',0)->field('id,warehouse_kingdee_code,goods_kingdee_code,inventory_quantity')->select();

                if(!$stockData){//没有数据同步库存到数据库

                    $insertUnitList = array_values($insertUnitList);

                    if($insertUnitList){

                        Db::name('shop_goods_stock')->insertAll($insertUnitList);

                    }

                }else{//有数据开始对比 一样的更新，不一样的修改

                    foreach($stockData as $stock){

                        $stockKey = $stock['warehouse_kingdee_code'].'_'.$stock['goods_kingdee_code'];

                        if(isset($insertUnitList[$stockKey])){//存在



                            if($stock['inventory_quantity'] != $insertUnitList[$stockKey]['inventory_quantity']){

                                Db::name('shop_goods_stock')->where('warehouse_kingdee_code','=',$stock['warehouse_kingdee_code'])

                                    ->where('goods_kingdee_code','=',$stock['goods_kingdee_code'])->update(['inventory_quantity' => $insertUnitList[$stockKey]['inventory_quantity'],'update_time' => time()]);

                            }

                            unset($insertUnitList[$stockKey]);

                        }

                    }



                    //如果有新的仓库优惠券库存需要插入数据库

                    if(!empty($insertUnitList)){

                        $insertUnitList = array_values($insertUnitList);

                        if($insertUnitList){

                            Db::name('shop_goods_stock')->insertAll($insertUnitList);

                        }

                    }



                }



            }

            return true;



        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }



    }



    /**

     * 导入优惠券

     * @param $param

     * @return bool

     * @author Mr.Li

     * @create 2021-09-07 13:49

     */

    public function import($param)

    {
        $shop_id = DB::name('shop')->where('shop_name',$param[0][0])->value('shop_id');
        if(empty($shop_id)){
            $this->error = '门店不存在';
            return false;
        }
        $error_customer = [];
        Db::startTrans();
        try {
            foreach($param as $v){
                $where = [
                    ['shop_id','=',$shop_id],
                    ['king_no','=',$v[1]]
                ];
                $info = DB::name('customer')->where($where)->value('id');
                if(!empty($info)){
                    $insert = $update =  [];
                    $insert['is_show_balance'] = $update['is_show_balance'] = $v[3] == '是' ?1:0;
                    $insert['create_time'] = $update['update_time'] = time();
                    $insert['king_no'] = $v[1];
                    $insert['shop_id'] = $shop_id;
                    $insert['customer_id'] = $info;
                    DB::name('customer')->where($where)->update($update);
                    DB::name('customer_show_balance_log')->insert($insert);

                }else{
                    array_push($error_customer,$v[1]);
                }

            }
            Db::commit();

            echo "添加成功";

            print_r($error_customer);
            exit();

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;
        }





        // 验证

        $categoryId = 51;

        $userId = 1;

        $insertGoods = [];

        $goodsType = ['定制' => 0,'标品' => 1];

        $time = time();

        foreach($param as $v){

            $insertGoods[] = [

                'is_standard_product'       => $goodsType[$v[0]] ?? '',

                'name'                      => $v[1] ?? '',

                'desc'                      => $v[2] ?? '',

                'spec_big_name'             => $v[3] ?? '',

                'spec_small_name'           => $v[4] ?? '',

                'unit_code'                 => $v[5] ?? '',

                'small_unit_price'          => $v[6] ?? '',

                'price'                     => $v[7] ?? '',

                'kingdee_stock_unit'        => $v[8] ?? '',

                'kingdee_code'              => $v[9] ?? '',

                'trans_coefficient'         => $v[10] ?? '',

                'sample_unit'               => $v[11] ?? '',

            ];

        }

        try {





            $goodsValidate = new \app\admin\validate\Coupon();

            $skuValidate = new \app\admin\validate\CouponSku();

            foreach($insertGoods as $goods){

                if (!$goodsValidate->scene('batch_create')->check($goods)) {

                    $this->error = $goodsValidate->getError();

                    return false;

                }



                if (!$skuValidate->scene('batch_create')->check($goods)) {

                    $this->error = $skuValidate->getError();

                    return false;

                }

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $unitCodes = array_column($insertGoods,'unit_code');

        if($unitCodes){

            $unitData = Db::name('shop_goods_unit')->where('big_unit_code','in',$unitCodes)->column('unit_id','big_unit_code');

        }

        $specNames = array_column($insertGoods,'spec_big_name');

        if($specNames){

            $specData = Db::name('shop_goods_spec')->where('name','in',$specNames)->column('item_id','name');

        }

        Db::startTrans();

        $time = time();

        try {

            foreach ($insertGoods as $goods){

                $unitId = $unitData[$goods['unit_code']] ?? '';

                if(!$unitId){

                    throw new \Exception('单位编码不存在,请确认是否正确');

                }

                // 验证

                $data = [

                    'name'                  => trim($goods['name']),

                    'category_id'           => $goods['is_standard_product'] ? 1 : 2 ,

                    'desc'                  => $goods['desc'],

                    'content'               => '',

                    'sort'                  => 0,

                    'thumb_image'           => '',

                    'share_image'           => '',

                    'image'                 => '',

                    'create_user_id'        =>  $userId,

                    'status'                => 1,

                    'update_time'           => $time,

                    'create_time'           => $time,

                    'is_standard_product'   => $goods['is_standard_product']

                ];

                $goodsObj = $this->create($data);

                if ($goodsObj) {

                    $this->addActionRecord(1,'shop_goods_create',$goodsObj->id,'添加优惠券' .$data['name'],'shop','goods');

                }

            }

            $this->error = '添加成功';

            Db::commit();

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        return true;

    }

    // 一键发放会员优惠券
    public function oneProvide($request){

        $operator_id=$request['user']['id'];

        $nowYear = date('Y',time());

        $nowMonth = date('m',time());

        $nextYear = $nowYear+1;

        $mon = [
            '01' => [$nowYear.'-1',$nowYear.'-4'],
            '02' => [$nowYear.'-1',$nowYear.'-4'],
            '03' => [$nowYear.'-1',$nowYear.'-4'],
            '04' => [$nowYear.'-4',$nowYear.'-7'],
            '05' => [$nowYear.'-4',$nowYear.'-7'],
            '06' => [$nowYear.'-4',$nowYear.'-7'],
            '07' => [$nowYear.'-7',$nowYear.'-10'],
            '08' => [$nowYear.'-7',$nowYear.'-10'],
            '09' => [$nowYear.'-7',$nowYear.'-10'],
            '10' => [$nowYear.'-10',$nextYear.'-1'],
            '11' => [$nowYear.'-10',$nextYear.'-1'],
            '12' => [$nowYear.'-10',$nextYear.'-1'],
        ];


        $tag = $mon[$nowMonth];

        $addData = [];

        $start_time = strtotime($tag[0].'-1');

        $end_time = strtotime($tag[1].'-1');

        $where = [];

        array_push($where,['start_time','between',"$start_time,$end_time"]);

        array_push($where,['is_vip','=','1']);


        $vipCards = Db::name('coupon')->where($where)->select()->toArray();



        if($vipCards){

            // echo "卡项已创建";

        }else{
            // 产品兑换券-白玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '4';
            $addCard['name'] = '产品兑换券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '1';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '白玉兰';
            $addCard['goodsList'] = [
                '0' => [
                    'id' => '586',
                ],
                '1' => [
                    'id' => '587',
                ],
            ];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 项目代金券-白玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '项目代金券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '200';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '白玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 产品兑换券-紫玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '4';
            $addCard['name'] = '产品兑换券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '1';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '紫玉兰';
            $addCard['goodsList'] = [
                '0' => [
                    'id' => '586',
                ],
                '1' => [
                    'id' => '587',
                ],
                '2' => [
                    'id' => '557',
                ],
            ];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 项目代金券-紫玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '项目代金券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '300';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '紫玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 光电美肤券-紫玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '光电美肤券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '500';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '紫玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 光电闺蜜券-紫玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '光电闺蜜券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '500';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '紫玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 产品兑换券-金玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '4';
            $addCard['name'] = '产品兑换券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '1';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '金玉兰';
            $addCard['goodsList'] = [
                '0' => [
                    'id' => '586',
                ],
                '1' => [
                    'id' => '587',
                ],
                '2' => [
                    'id' => '557',
                ],
                '3' => [
                    'id' => '564',
                ]
            ];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 项目代金券-金玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '项目代金券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '500';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '金玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 光电美肤券-金玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '光电美肤券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '500';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '金玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);

            // 光电闺蜜券-金玉兰-----------------------------------------------------------------------------------
            $addCard = [];

            $addCard['type'] = '1';
            $addCard['name'] = '光电闺蜜券';
            $addCard['use_threshold'] = '0';
            $addCard['denomination'] = '500';
            $addCard['limit_number'] = '1';
            $addCard['sequence'] = '';
            $addCard['valid'] = '1';
            $addCard['use_type'] = '2';
            $addCard['goods_type'] = '1';
            $addCard['start_time'] = $tag[0].'-1';
            $addCard['end_time'] = $tag[1].'-1';
            $addCard['desc'] = '金玉兰';
            $addCard['goodsList'] = [];
            $addCard['user'] = $request['user'];
            $addCard['is_vip'] = '1';

            array_push($addData,$addCard);


            foreach ($addData as $key => $value) {

                $this->addData($value);

            }

            // 优惠券创建完毕

            $where = [];

            array_push($where,['start_time','between',"$start_time,$end_time"]);

            array_push($where,['is_vip','=','1']);


            $vipCards = Db::name('coupon')->where($where)->select()->toArray();

        }

        $couponIds = array_values(array_unique(array_column($vipCards,'id')));

        // echo "<pre>";
        // print_r($vipCards);
        // echo "</pre>";
        // exit;

        $white = [];
        $purple = [];
        $gold = [];

        foreach ($vipCards as $key => $value) {
            $color = $value['desc'];

            if($color == '白玉兰'){
                array_push($white,$value['id']);
            }

            if($color == '紫玉兰'){
                array_push($purple,$value['id']);
            }

            if($color == '金玉兰'){
                array_push($gold,$value['id']);
            }
        }



        $sendRes = [];

        foreach ($vipCards as $key => $value) {
            $color = $value['desc'];

            $provideCustomerList = [];

            $one = [];

            $one['name'] = $value['name'];

            $one['vipType'] = $value['desc'];

            $provideDataList['coupon_id'] = $value['id'];

            $provideDataList['data_id'] = '';

            $provideDataList['data_name'] = '一键发放'.$value['name'].'【'.$value['desc'].'】';

            $provideDataList['provide_create_user_id'] = $operator_id;

            $provideDataList['create_time'] = time();


            $customer_ids = $this->getVipCustomerIds($value['desc']);

            $one['should_send'] = count($customer_ids);

            $provideDataList['should_send'] = count($customer_ids);

            Db::startTrans();

            try {

                $provide = Db::name('coupon_provide')->insertGetId($provideDataList);

                //发放创建成功，处理会员发券

                if ($provide)
                {

                    $customers = $customer_ids;

                    $had_cardIds = [];

                    if($color == '白玉兰'){
                        $had_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','=',$value['id']],['customer_id','in',$customers]])->column('customer_id');
                    }

                    if($color == '紫玉兰'){
                        $had_w_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','in',$white],['customer_id','in',$customers]])->column('customer_id');
                        $had_p_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','=',$value['id']],['customer_id','in',$customers]])->column('customer_id');
                        $had_g_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','in',$gold],['customer_id','in',$customers]])->column('customer_id');

                        $had_cardIds = array_merge($had_w_cardIds,$had_p_cardIds,$had_g_cardIds);
                    }

                    if($color == '金玉兰'){
                        $had_w_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','in',$white],['customer_id','in',$customers]])->column('customer_id');
                        $had_p_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','in',$purple],['customer_id','in',$customers]])->column('customer_id');
                        $had_g_cardIds = Db::name('coupon_provide_customer')->where([['coupon_id','=',$value['id']],['customer_id','in',$customers]])->column('customer_id');

                        $had_cardIds = array_merge($had_w_cardIds,$had_p_cardIds,$had_g_cardIds);
                    }



                    // echo "<pre>";
                    // print_r($had_cardIds);
                    // echo "</pre>";
                    // exit;
                    $customers = array_diff($customers,$had_cardIds);

                    if(count($customers)<'1'){

                        $one['actual_send'] = count($customers);

                        $one['cause'] = '所选客户已经发放';

                        $one['customerIds'] = $customers;

                        array_push($sendRes,$one);
                        // $this->error = '所选客户已经发放该优惠券了，请勿重复发放！';

                        // return false;

                        Db::rollback(); // 回滚

                        continue;

                    }

                    foreach ($customers as $k => $v) {

                        $provideCustomerList[$k]['coupon_id'] = $value['id'];

                        $provideCustomerList[$k]['create_time'] = time();

                        $provideCustomerList[$k]['customer_id'] = $v;

                    }

                    $res = Db::name('coupon_provide_customer')->insertAll($provideCustomerList);

                    $save = [

                        'actual_send' => $res,

                    ];

                    $provide_bool = Db::name('coupon_provide')->where(['id'=>$provide])->update($save);

                    Db::commit();

                    $one['actual_send'] = $res;

                    $one['cause'] = '';

                    array_push($sendRes,$one);

                }

            } catch (\Exception $e) {
                //throw $th;

                Db::rollback(); // 回滚

            }



            // exit;
        }

        return $sendRes;

    }

    public function getVipCustomerIds($vipTitl){

        $where = [];

        array_push($where,['join_time','<',time()]);

        array_push($where,['be_overdue_time','>',time()]);

        switch ($vipTitl) {

            case '白玉兰':

                array_push($where,['membership_leve','=','1']);

                break;

            case '紫玉兰':

                array_push($where,['membership_leve','=','2']);

                break;

            case '金玉兰':

                array_push($where,['membership_leve','=','3']);

                break;

        }

        $vipCustomerList = Db::name('customer')->where($where)->column('id');

        return $vipCustomerList;

    }

}

